package com.yihaodian.search.facet.merger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.yihaodian.api.search.SearchRequest;
import com.yihaodian.api.search.facet.FacetResult;
import com.yihaodian.search.broker.shard.ShardSearchResponse;

public class Collector {
	/**
	 * Collect the facet result with the same facet name, put them in list.
	 */
	public static Map<String, List<FacetResult>> collectFacets(SearchRequest request,
			List<ShardSearchResponse> shardResplist){
		HashMap<String, List<FacetResult>> facetResultMap = 
			new HashMap<String, List<FacetResult>>();
		
		for (ShardSearchResponse shardResp : shardResplist) {
			Map<String, FacetResult> shardResultMap = 
				shardResp.getSearchResponse().getFacetResultMap();
			if (shardResultMap == null) {
				continue;
			}
			
			Iterator<String> resultIt = shardResultMap.keySet().iterator();
			while (resultIt.hasNext()) {
				String label = resultIt.next();
				FacetResult fr = shardResultMap.get(label);
				
				List<FacetResult> frs = facetResultMap.get(label);
				if (frs == null) {
					facetResultMap.put(label, new ArrayList<FacetResult>());
					frs = facetResultMap.get(label);
				}
				frs.add(fr);
			}
		}
		
		return facetResultMap;
	}
}
